package cn.tramy.pinxian.task.domain.model

import cn.tramy.pinxian.common.exception.CommonException
import cn.tramy.pinxian.common.util.validationRules
import cn.tramy.pinxian.task.domain.event.TaskCreated
import cn.tramy.pinxian.task.domain.event.TaskDeleted
import cn.tramy.pinxian.task.domain.event.TaskFinished
import cn.tramy.pinxian.wind.domain.model.BaseDeletableDomainModel
import java.time.LocalDateTime
import javax.persistence.Entity

@Entity
class Task(uid: String, val content: String, val timer: LocalDateTime?, deleted: Boolean = false, createAt: LocalDateTime) : BaseDeletableDomainModel(uid, deleted, createAt) {

    private var finished: Boolean = false

    init {
        this.apply(TaskCreated(uid, content, timer, deleted, finished, createdAt))
    }

    fun finish() {
        validationRules {
            rule {
                ifTrue { finished }
                exception { CommonException("Task[$uid] has finished.") }
            }
        }.validate()

        if (!this.finished) {
            this.finished = true
            this.apply(TaskFinished(this.uid, this.content))
        }
    }

    fun delete() {

        validationRules {
            rule {
                ifTrue { deleted }
                exception { CommonException("Task[$uid] has been deleted.") }
            }
        }

        this.baseDelete()
        this.apply(TaskDeleted(uid, content))
    }

}